"use strict"

var fs 		= 	require('fs'),
	log		=	console.log
	

exports.storeMove = function(payload) {
	var folder = "stored-moves/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	log("stored move: " + payload)
	
	fs.writeFileSync(
		folder + gameId + ".txt",				//location on the fs
		payload,								//json blob to store (should already be encoded)
		'utf8'									//encoding
	)
	
	return true
}

exports.retrieveMove = function(payload) {
	var folder = "stored-moves/",
		move = JSON.parse(payload),
		gameId = move.gameId
	
	try {
		var data = fs.readFileSync(
			folder + gameId + ".txt",			//location on the fs
			'utf8'								//encoding
		)
	} catch(e) {
		//don't need to process this error, just do nothing
	}
	
	return ( data ? data : false )				//return 'false' if no data retrieved
}

exports.storeGame = function(payload) {
	var folder = "stored-games/",
		game = JSON.parse(payload)
	
	//log("stored game: " + payload)
	
	// force update of last access time
	var cTime = new Date().getTime()
	game.lastUpdated = cTime
	var newPayload = JSON.stringify(game)
	
	// save in the filesystem
	fs.writeFileSync(
		folder + game.gameId + ".txt",			//location on the fs
		newPayload,								//json blob to store (should already be encoded)
		'utf8'									//encoding
	)
	
	return true
}

exports.retrieveGame = function(payload) {
	var folder = "stored-games/",
		move = JSON.parse(payload),
		gameId = move.gameId,
		data = null
	
	try {
		data = fs.readFileSync(
			folder + gameId + ".txt",				//location on the fs
			'utf8'									//encoding
		)
	} catch(e) {
		log("retrieveGame error: couldn't retrieve game '" + folder + gameId + ".txt'")
	}
	
	return ( data ? data : false )					//return 'false' if no data retrieved
}

exports.gamesList = function(gametype) {
	var folder = "stored-games/",
		gamesList = [ ]
	
	// create a new regular expression pattern using the gameType
	var expr = gametype + ".*.txt",
		regexp = new RegExp(expr)
	
	// create list of all files in a directory
	var files = fs.readdirSync(folder)
	
	var data, json
	for (var i=0, ii=files.length; i<ii; i++) {
	
		// filter using the gametype
		//log( files[i] + " : " + regexp.test(files[i]) )
		if ( ! regexp.test(files[i]) )  continue
		
		data = fs.readFileSync(folder + files[i], 'utf8')
		json = JSON.parse(data)									//load each game and parse to json
		if (json.players.length < 2) {
			gamesList.push(json)								//add only games which have 1 (or 0) players
		}
	}
	
	return { games: gamesList }									//return games list in correct format
}